package com.waimai.app.qa.listener;


import org.testng.IRetryAnalyzer;
import org.testng.ITestResult;

import com.waimai.app.qa.support.ScreenRecoder;
import com.waimai.app.qa.util.Logger;

/**
 * 监听跑一次失败后, 重跑三次,累计执行4次
 * 在retry方法里，判断Retry次数是否已经超过指定的最大retry次数。如果没有返回true，否则返回false。
 * @author aihui
 */
public class RetryTestAnalyzer extends ListenerAdapter implements IRetryAnalyzer {

	public static ScreenRecoder screenRecoder = null;
	
	//获取CONFIG配置文件中screenRecoder是否打开录制信息
	public String on = System.getProperty("on") ;
	private int count = 1;
	private int maxCount = 3;
	
	//private static final String TEST_RETRY_COUNT = "testRetryCount";
	/*public RetryTestAnalyzer() {
		String retryMaxCount = System.getProperty(TEST_RETRY_COUNT);
		if (retryMaxCount != null) {
			maxCount = Integer.parseInt(retryMaxCount);
		}
	}*/

	public int getCount() {
		return this.count;
	}

	public int getMaxCount() {
		return this.maxCount;
	}
	
	public synchronized boolean retry(ITestResult result) {
		String testClassName = String.format("%s.%s", result.getMethod().getRealClass().toString(), result.getMethod().getMethodName());
		
		//监听仅当第二次失败后,第三次执行时开始录屏
		if(count <= maxCount) {	
			if(count==maxCount && on.equals("true")){
				screenRecoder = new ScreenRecoder();
				//ScreenRecoder scr= new ScreenRecoder();
				try {
					
					Logger.Defaultlog("开始录屏");
					screenRecoder.startRecording();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			result.setAttribute("RETRY", new Integer(count));
			Logger.Defaultlog("[RETRYING] " + testClassName + " FAILED, " + "Retrying " + count + " time");
			count += 1;
			return true;
		}
		
		//第三次结束时停止录屏
		if(screenRecoder !=null && on.equals("true")){
			try {
				Logger.Defaultlog("停止录屏");
				screenRecoder.stopRecording();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		onTestFailure(result);
		return false;
	}
} 